import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _initializerDefineProperty from "@babel/runtime/helpers/esm/initializerDefineProperty";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _initializerWarningHelper from "@babel/runtime/helpers/esm/initializerWarningHelper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
var _excluded = ["dataType"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _class, _class2, _descriptor;

import React from 'react';
import { Button, Col, Form, Input, Row, Spin, Table, InputNumber, DatePicker, Select } from 'antd';
import moment from 'moment';
import qs from 'querystring';
import { Bind } from 'lodash-decorators';
import { createPagination, getCurrentOrganizationId, getResponse, getDateFormat, getDateTimeFormat } from "../../utils/utils";
import intl from "../../utils/intl";
import { DEFAULT_DATETIME_FORMAT, DEFAULT_DATE_FORMAT } from "../../utils/constants";
import { yesOrNoRender } from "../../utils/renderer";
import "./index.less";
import { queryLovData } from "../../services/api";
var FormItem = Form.Item;
var formItemLayout = {
  labelCol: {
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    sm: {
      span: 14
    }
  }
};
var defaultRowKey = 'lovId';
var LovModal = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(LovModal, _React$Component);

  var _super = _createSuper(LovModal);

  function LovModal(props) {
    var _this;

    _classCallCheck(this, LovModal);

    _this = _super.call(this, props);

    _initializerDefineProperty(_this, "setChildren", _descriptor, _assertThisInitialized(_this));

    _this.state = {
      selectedRows: [],
      list: [],
      treeKeys: [],
      pagination: {},
      loading: false
    };
    return _this;
  }

  _createClass(LovModal, [{
    key: "setSateData",
    value: function setSateData(state) {
      if (this.mounted) {
        this.setState(state);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.mounted = true;
    }
  }, {
    key: "loadOnFirstVisible",
    value: function loadOnFirstVisible() {
      var delayLoadFlag = this.props.lov.delayLoadFlag;

      if (this.mounted && !delayLoadFlag) {
        this.queryData();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.mounted = false;
    }
  }, {
    key: "onSelectChange",
    value: function onSelectChange(selectedRowKeys, selectedRows) {
      // TODO: 支持多选
      var record = selectedRows[0];
      this.props.onSelect(record);
      this.setState({
        selectedRows: [record]
      });
    }
  }, {
    key: "handleRowClick",
    value: function handleRowClick(record) {
      this.selectRecord(record);
    }
  }, {
    key: "selectRecord",
    value: function selectRecord(record) {
      this.props.onSelect(record);
      this.setState({
        selectedRows: [record]
      });
    }
  }, {
    key: "handleRowDoubleClick",
    value: function handleRowDoubleClick(record) {
      this.selectRecord(record);
      this.props.onClose();
    }
  }, {
    key: "hideLoading",
    value: function hideLoading() {
      this.setState({
        loading: false
      });
    }
  }, {
    key: "queryData",
    value: function queryData() {
      var _this2 = this;

      var pagination = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var filter = this.props.form.getFieldsValue();
      var _this$props$lov = this.props.lov,
          queryUrl = _this$props$lov.queryUrl,
          pageSize = _this$props$lov.pageSize,
          lovCode = _this$props$lov.lovCode,
          lovTypeCode = _this$props$lov.lovTypeCode,
          _this$props$lov$query = _this$props$lov.queryFields,
          queryFields = _this$props$lov$query === void 0 ? [] : _this$props$lov$query;
      var _this$props$queryPara = this.props.queryParams,
          queryParams = _this$props$queryPara === void 0 ? {} : _this$props$queryPara;
      var nowQueryParams = queryParams || {};

      if (_isFunction(nowQueryParams)) {
        nowQueryParams = nowQueryParams();
      }

      var queryIndex = queryUrl.indexOf('?');
      var sourceQueryParams = {};

      if (queryIndex !== -1) {
        sourceQueryParams = qs.parse(queryUrl.substr(queryIndex + 1));
      }

      var formatFilter = _objectSpread({}, filter);

      queryFields.forEach(function (item) {
        if (item.dataType === 'DATE' || item.dataType === 'DATETIME') {
          if (filter[item.field]) {
            formatFilter[item.field] = moment(filter[item.field]).format(item.dataType === 'DATETIME' ? DEFAULT_DATETIME_FORMAT : DEFAULT_DATE_FORMAT);
          }
        }
      });

      var sourceParams = _objectSpread(_objectSpread(_objectSpread({}, formatFilter), {}, {
        page: pagination.current - 1 || 0,
        size: pagination.pageSize || pageSize
      }, sourceQueryParams), nowQueryParams);

      var params = lovTypeCode !== 'URL' ? Object.assign(sourceParams, {
        lovCode: lovCode
      }) : sourceParams;
      /**
       * 替换查询 Url 中的变量
       * @param {String} url
       * @param {Object} data
       */

      function getUrl(url, data) {
        var ret = url;
        var organizationRe = /\{organizationId\}|\{tenantId\}/g;
        Object.keys(data).map(function (key) {
          var re = new RegExp("{".concat(key, "}"), 'g');
          ret = ret.replace(re, data[key]);
          return ret;
        });

        if (organizationRe.test(ret)) {
          ret = ret.replace(organizationRe, getCurrentOrganizationId());
        }

        var index = ret.indexOf('?'); // 查找是否有查询条件

        if (queryIndex !== -1) {
          ret = ret.substr(0, index);
        }

        return ret;
      }

      var url = getUrl(queryUrl, queryParams);
      this.setState({
        loading: true
      }, function () {
        queryLovData(url, params).then(function (res) {
          if (getResponse(res)) {
            _this2.dataFilter(res);
          }
        }).then(function () {
          // 还需要将 Lov 的选中数据清空
          var onSelect = _this2.props.onSelect;
          onSelect();

          _this2.setState({
            selectedRows: []
          });
        }).finally(function () {
          _this2.hideLoading();
        });
      });
    }
  }, {
    key: "formReset",
    value: function formReset() {
      this.props.form.resetFields();
    }
    /**
     * 树 child 属性更改
     * @param {Array} list 原树结构数据
     * @param {String} childName 要替换的 childName
     */

  }, {
    key: "dataFilter",
    value:
    /**
     * 处理返回列表数据
     * @param {Object|Array} data - 返回的列表数据
     */
    function dataFilter(data) {
      var _this$props$lov2 = this.props.lov,
          _this$props$lov2$valu = _this$props$lov2.valueField,
          rowkey = _this$props$lov2$valu === void 0 ? defaultRowKey : _this$props$lov2$valu,
          childrenFieldName = _this$props$lov2.childrenFieldName;

      var isTree = _isArray(data);

      var hasParams = !_isEmpty(Object.values(this.props.form.getFieldsValue()).filter(function (e) {
        return e !== undefined && e !== '';
      }));
      var list = isTree ? this.setChildren(data, childrenFieldName) : data.content;
      var pagination = !isTree && createPagination(data);
      var treeKeys = []; // 树状 key 列表

      if (isTree && hasParams) {
        /**
         * 遍历生成树列表
         * @param {*} treeList - 树列表数据
         */
        var flatKeys = function flatKeys(treeList) {
          if (_isArray(treeList.children) && !_isEmpty(treeList.children)) {
            treeKeys.push(treeList[rowkey]);
            treeList.children.forEach(function (item) {
              return flatKeys(item);
            });
          } else {
            treeKeys.push(treeList[rowkey]);
          }
        };

        list.forEach(function (item) {
          return flatKeys(item);
        }); // 遍历生成 key 列表
      }

      this.setSateData({
        list: list,
        treeKeys: treeKeys,
        pagination: pagination
      });
    }
  }, {
    key: "defineProperty",
    value: function defineProperty(obj, property, value) {
      Object.defineProperty(obj, property, {
        value: value,
        writable: true,
        enumerable: false,
        configurable: true
      });
    }
    /**
     * 访问对象由字符串指定的多层属性
     * @param {Object} obj 访问的对象
     * @param {String} str 属性字符串，如 'a.b.c.d'
     */

  }, {
    key: "parseField",
    value: function parseField(obj, str) {
      if (/[.]/g.test(str)) {
        var arr = str.split('.');
        var newObj = obj[arr[0]];
        var newStr = arr.slice(1).join('.');
        return this.parseField(newObj, newStr);
      }

      return obj[str];
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props = this.props,
          _this$props$lov3 = _this$props.lov,
          _this$props$lov3$valu = _this$props$lov3.valueField,
          rowkey = _this$props$lov3$valu === void 0 ? defaultRowKey : _this$props$lov3$valu,
          _this$props$lov3$tabl = _this$props$lov3.tableFields,
          tableFields = _this$props$lov3$tabl === void 0 ? [] : _this$props$lov3$tabl,
          _this$props$lov3$quer = _this$props$lov3.queryFields,
          queryFields = _this$props$lov3$quer === void 0 ? [] : _this$props$lov3$quer,
          _this$props$ldpData = _this$props.ldpData,
          ldpData = _this$props$ldpData === void 0 ? {} : _this$props$ldpData,
          getFieldDecorator = _this$props.form.getFieldDecorator,
          lovLoadLoading = _this$props.lovLoadLoading,
          width = _this$props.width,
          _this$props$queryInpu = _this$props.queryInputProps,
          queryInputProps = _this$props$queryInpu === void 0 ? {} : _this$props$queryInpu,
          _this$props$isDbc2Sbc = _this$props.isDbc2Sbc,
          isDbc2Sbc = _this$props$isDbc2Sbc === void 0 ? false : _this$props$isDbc2Sbc;

      if (lovLoadLoading) {
        return /*#__PURE__*/React.createElement(Spin, {
          spinning: true
        });
      }

      var _this$state = this.state,
          _this$state$list = _this$state.list,
          list = _this$state$list === void 0 ? [] : _this$state$list,
          selectedRows = _this$state.selectedRows,
          loading = _this$state.loading,
          pagination = _this$state.pagination,
          treeKeys = _this$state.treeKeys;

      var isTree = _isArray(list);

      var rowSelection = {
        type: 'radio',
        selectedRowKeys: selectedRows.map(function (n) {
          return _this3.parseField(n, rowkey);
        }),
        onChange: this.onSelectChange
      };
      var tableProps = {
        loading: loading,
        rowSelection: rowSelection,
        pagination: pagination,
        bordered: true,
        dataSource: list,
        columns: tableFields.map(function (item) {
          var dataType = item.dataType,
              rest = _objectWithoutProperties(item, _excluded);

          return dataType === 'SWITCH' ? _objectSpread(_objectSpread({}, rest), {}, {
            render: yesOrNoRender
          }) : rest;
        }),
        onRow: function onRow(record, index) {
          return {
            onDoubleClick: function onDoubleClick() {
              return _this3.handleRowDoubleClick(record, index);
            },
            onClick: function onClick() {
              return _this3.handleRowClick(record, index);
            }
          };
        },
        onChange: this.queryData
      };
      var treeProps = isTree ? {
        uncontrolled: true,
        expandedRowKeys: treeKeys
      } : {}; // 查询条件表单

      var span = queryFields.length <= 1 || width <= 400 ? 24 : 12;
      var queryInput = queryFields.map(function () {
        var queryItem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var valueListData = ldpData[queryItem.sourceCode] || [];

        switch (queryItem.dataType) {
          case 'INT':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(InputNumber, {
              style: {
                width: '100%'
              },
              onPressEnter: _this3.queryData
            }))));

          case 'DATE':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(DatePicker, {
              style: {
                width: '100%'
              },
              placeholder: "",
              format: getDateFormat()
            }))));

          case 'DATETIME':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(DatePicker, {
              style: {
                width: '100%'
              },
              placeholder: "",
              showTime: {
                format: DEFAULT_DATETIME_FORMAT
              },
              format: getDateTimeFormat()
            }))));

          case 'SELECT':
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(Select, {
              allowClear: true,
              style: {
                width: '100%'
              }
            }, valueListData.map(function (item) {
              return /*#__PURE__*/React.createElement(Select.Option, {
                value: item.value,
                key: item.value
              }, item.meaning);
            })))));

          default:
            return /*#__PURE__*/React.createElement(Col, {
              span: span,
              key: queryItem.field
            }, /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
              label: queryItem.label
            }), getFieldDecorator(queryItem.field)( /*#__PURE__*/React.createElement(Input, Object.assign({
              dbc2sbc: isDbc2Sbc
            }, queryInputProps)))));
        }
      });
      return /*#__PURE__*/React.createElement(Form, null, queryFields.length > 0 ? /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          marginBottom: '10px',
          alignItems: 'flex-start'
        }
      }, /*#__PURE__*/React.createElement(Row, {
        style: {
          flex: 'auto'
        }
      }, queryInput), /*#__PURE__*/React.createElement("div", {
        className: "lov-modal-btn-container"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.formReset,
        style: {
          marginRight: 8
        }
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.queryData
      }, intl.get('cpaas.common.button.search').d('查询')))) : null, /*#__PURE__*/React.createElement(Table, Object.assign({
        resizable: false,
        rowKey: function rowKey(record) {
          return _this3.parseField(record, rowkey);
        }
      }, tableProps, treeProps)));
    }
  }]);

  return LovModal;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "loadOnFirstVisible", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "loadOnFirstVisible"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onSelectChange", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "onSelectChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRowClick", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRowClick"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRowDoubleClick", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRowDoubleClick"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "queryData", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "queryData"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "formReset", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "formReset"), _class2.prototype), _descriptor = _applyDecoratedDescriptor(_class2.prototype, "setChildren", [_dec8], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function initializer() {
    var _this4 = this;

    return function (data, childName) {
      return childName ? data.map(function (n) {
        var item = n;

        if (!_isEmpty(n[childName])) {
          _this4.defineProperty(item, 'children', [_objectSpread({}, n[childName])]);
        }

        if (!_isEmpty(item.children)) {
          item.children = _this4.setChildren(item.children);
        }

        return item;
      }) : data;
    };
  }
}), _applyDecoratedDescriptor(_class2.prototype, "dataFilter", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "dataFilter"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "defineProperty", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "defineProperty"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "parseField", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "parseField"), _class2.prototype)), _class2)) || _class);
export default LovModal;